/**
 * Created by Jaye on 2018/02/08.
 */

var addApis = [];
var deleteApis = [];
$(function () {
    var oTable1 = $('#commodityListTable').dataTable(
        {
            "bPaginage": true,//分页工具条显示
            "sPaginationType": "full_numbers",//分页工具条样式
            "bStateSave": true, //是否打开客户端状态记录功能,此功能在ajax刷新纪录的时候不会将个性化设定回复为初始化状态
            "bScrollCollapse": true, //当显示的数据不足以支撑表格的默认的高度
            "bLengthChange": true, //每页显示的记录数
            "bFilter": true, //搜索栏
            "bSort": true, //是否支持排序功能
            "bInfo": true, //显示表格信息
            "bAutoWidth": true, //自适应宽度
            "bJQueryUI": false,//是否开启主题
            "bDestroy": true,
            // "ajax": {
            //     "url": "/api/list",
            //     "type": "post",
            //     "data": '{"data":"123"}'
            // },
            "bProcessing": true, //开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
            "sAjaxDataProp": "data",//是服务器分页的标志，必须有
            "sAjaxSource": "/commodity/list",//通过ajax实现分页的url路径。
            "bServerSide": true,//服务器处理分页，默认是false，需要服务器处理，必须true
            "fnServerData": function (sSource, aoData, fnCallback) {
                $.ajax({
                    type: "post",
                    url: sSource,
                    dataType: "json",
                    data: {"aodata": JSON.stringify(aoData)},
                    success: function (resp) {
                        fnCallback(resp);
                    }
                });

            },
            "aoColumns": [//初始化要显示的列
                // {
                //     "mDataProp": "id",//获取列数据，跟服务器返回字段一致
                //     "sClass": "center",//显示样式
                //     "mRender": function (data, type, full) {//返回自定义的样式
                //         return "<label><input type='checkbox' class='ace' /><span class='lbl'></span></label>"
                //     }
                // },
                {
                    "sClass": "text-center",
                    "data": "ID",
                    "render": function (data, type, full, meta) {
                        return '<input type="radio" name="checkchild" class="checkchild"  value="" />';
                    }
                },
                {
                    title: "商品Id",
                    "sClass": "text-center commodityId",
                    "mDataProp": "commodityId"
                },
                {
                    title: "商品名称",
                    "sClass": "text-center",
                    "mDataProp": "commodityName"
                },
                {
                    title: "有效时长(s)",
                    "sClass": "text-center",
                    "mDataProp": "term"
                },
                {
                    title: "价格(元)",
                    "sClass": "text-center",
                    "mDataProp": "price"
                },
                {
                    title: "操  作",
                    "sClass": "text-center",
                    "mDataProp": "operation",
                    "mRender": function (data, type, row) {
                        return "<span type='text' class='btn btn-primary btn-sm' onclick=detailCommodity(this)>查看详情</span>";
                    }
                }
            ],
            "fnRowCallback": function (nRow, aData, iDisplayIndex) {// 相当于对字段格式化
                // for (var i = 0; i < nRow.childElementCount; i++) {
                //     $('td:eq(' + i + ')', nRow).attr('style', 'text-align: center;');
                // }
            }
            ,
            "aoColumnDefs": [{//用来设置列一些特殊列的属性
                "bSortable": false,
                "aTargets": [0]
            }, {
                // "bSortable": false,
                // "aTargets": [5]
            }],
            "oLanguage": {//语言设置
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                }
                ,
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            }
        })
    ;

    $('#createCommodityModal').on('hide.bs.modal', function () {
        $('#commodityName').val("");
        $('#commodityDescription').val("");
        $('#price').val("");
        $('#term').val("");
        addApis = [];
        location.reload();
    });
    $('#createCommodityModal').on('show.bs.modal', function () {
        // alert(1);
        // alert(data.apis);
        $("#addApiPackagesTable").bootstrapTable('destroy');
        initAddApisTable();
    });
    $('#serviceModal').on('show.bs.modal', function () {
        $("#serviceTable").bootstrapTable({
            url: "/service/list",
            method: "post",
            height: "200",
            iconSize: "outline",
            search: true,
            showRefresh: true,
            showColumns: !0,
            singleSeclect: true,
            columns: [
                {radio: true},
                {
                    title: "服务Id",
                    field: "serviceId",
                    align: "center"
                }, {
                    title: "服务名称",
                    field: "serviceName",
                    align: "center"
                }],
            icons: {
                refresh: "glyphicon-repeat",
                toggle: "glyphicon-list-alt",
                columns: "glyphicon-list"
            }
        });
    });
    $('#detailButton').click(function () {
        var apiPackageId = $('#apiPackageListTable input:checked').parent().siblings('.apiPackageId').text();
        if (apiPackageId != "") {
            read_apiPackageDetail(apiPackageId);
            // initAddApisTable(); //重置table
            clearAddApisTable();
            initAddApisTable();
            //初始化缓存数组，
            addApis = [];
            deleteApis = [];
            return;
        }

        //     }
        // }
        swal({
            title: "请选择一列数据",
            type: "warning",
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认",
            closeOnConfirm: false
        });
    });
    $('#batchDeleteApisButton').on('click', function () {
        var ids = $.map($("#apisTable").bootstrapTable('getSelections'), function (row) {
            return row.apiId;
        });
        if (ids.length > 0) {
            $("#apisTable").bootstrapTable('remove', {
                field: 'apiId',
                values: ids
            });
            for (var i = 0; i < ids.length; i++) {
                deleteApis.push(ids[i]);
            }
        } else {
            tip_noselect();
        }
    });
    $('#batchAddApiPackagesButton').on('click', function () {
        $('#allApiPackagesTable').bootstrapTable('destroy');
        $('#allApiPackagesTable').bootstrapTable({
            url: "apipackage/list/all",
            method: "post",
            search: true,
            iconSize: "outline",
            showRefresh: true,
            showColumns: !0,
            columns: [
                {checkbox: true},
                {
                    title: "服务包Id",
                    field: "apiPackageId",
                    align: "center",
                    width: "300"
                }, {
                    title: "服务包名称",
                    field: "apiPackageName",
                    align: "center",
                    width: "200"
                }],
            icons: {
                refresh: "glyphicon-repeat",
                toggle: "glyphicon-list-alt",
                columns: "glyphicon-list"
            }
        });
        $("#apiPackagesModal").modal('show');
    });
});
function initApisTable(apis) {
    $('#apisTable').bootstrapTable('destroy');
    $('#apisTable').bootstrapTable({
        data: apis,
        height: {
            max: 200
        },
        search: true,
        iconSize: "outline",
        showRefresh: true,
        showColumns: !0,
        columns: [
            {checkbox: true},
            {
                title: "apiId",
                field: "apiId",
                align: "center",
                width: "300"
            }, {
                title: "api名称",
                field: "apiName",
                align: "center",
                width: "200"
            }, {
                title: "URL",
                field: "url",
                align: "center",
                width: "300"
            }, {
                title: "描述",
                field: "description",
                align: "center",
                width: "300"
            }],
        icons: {
            refresh: "glyphicon-repeat",
            toggle: "glyphicon-list-alt",
            columns: "glyphicon-list"
        }
    });

}
function read_apiPackageDetail(apiPackageId) {
    var data = {"apiPackageId": apiPackageId};
    $.ajax({
        url: "/apipackage/get",
        type: "post",
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (dat) {
            if (dat.code == 1000) {
                $('#api_packageId').val(apiPackageId);
                $('#api_packageName').val(dat.data.apiPackageName);
                initApisTable(dat.data.apis);
                $('#detailApiPackageModal').modal('show');
            } else {
                swal({
                    title: "查询服务包api失败",
                    type: "error",
                    buttons: false,
                    timer: 1000
                });
            }
            // $('#createApiPackageModal').modal('hide');
            // location.reload();
        },
        error: function (returndata) {
            swal({
                title: "发生错误",
                type: "error",
                buttons: false,
                timer: 1000
            });
            $('#createApiPackageModal').modal('hide');
        }
    });
}
function confirm_service() {
    var selectContent = $("#serviceTable").bootstrapTable('getSelections')[0];
    if (typeof(selectContent) == 'undefined') {
        // toastr.warning('请选择一列数据!');
        alert("请选择一列数据!");
        // $("#no_record").alert();
        return false;
    } else {
        // console.info(selectContent);
        $("#service_id").val(selectContent.serviceId);
        $("#service_name").val(selectContent.serviceName);
        $('#serviceModal').modal('hide');
        return;
    }
}
function CreateCommodity(commodityName, commodityDescription, price, term, addApis) {
    this.commodityName = commodityName;
    this.commodityDescription = commodityDescription;
    this.price = price;
    this.term = term;
    this.addApis = addApis;
}
function createCommodity() {
    // var formData = new FormData($("#form_data")[0]);
    var commodityName = $('#commodityName').val();
    var commodityDescription = $('#commodityDescription').val();
    var price = $('#price').val();
    var term = $('#term').val();
    var json = new CreateCommodity(commodityName, commodityDescription, price, term, addApis);
    $.ajax({
        url: "/commodity/create",
        type: "post",
        data: JSON.stringify(json),
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        dataType: "json",
        beforeSend: function () {
            // uploading = true;
        },
        success: function (data) {
            if (data.code == 1000) {
                swal({
                    title: "新增成功",
                    type: "success",
                    confirmButtonText: "确认",
                    closeOnConfirm: false
                }, function () {
                    $('#createCommodityModal').modal('hide');
                    location.reload();
                });
            } else {
                swal({
                    title: "新增失败",
                    type: "error",
                    buttons: false,
                    timer: 1000
                });
                return;
            }
            // location.reload();
        },
        error: function (returndata) {
            alert(returndata);
            $('#createCommodityModal').modal('hide');
        }
    });
}
function addApiPackagesButton() {
    var selectContent = $("#allApiPackagesTable").bootstrapTable('getSelections');
    if (typeof(selectContent) == 'undefined' || selectContent.length < 1) {
        tip_noselect();
        return false;
    } else {
        for (var i = 0; i < selectContent.length; i++) {
            addApiPackageRow(selectContent[i]);
        }
        $("#apiPackagesModal").modal('hide');
    }
}
function addApiPackageRow(data) {
    var index = $("#addApiPackagesTable").bootstrapTable('getData').length;
    if (index == 1) {
        initAddApisTable();
    }
    if (index > 0) {
        var havedData = $("#addApiPackagesTable").bootstrapTable('getData');
        for (var i = 0; i < index; i++) {
            if (havedData[i].apiPackageId == data.apiPackageId) {
                swal({
                    title: "Warning",
                    text: "部分数据已经存在，已跳过重复数据！",
                    type: "warning",
                    confirmButtonText: "确认",
                    closeOnConfirm: false
                });
                return;
            }
        }
    }
    $("#addApiPackagesTable").bootstrapTable('insertRow', {
        index: index,
        row: {
            apiPackageId: data.apiPackageId,
            apiPackageName: data.apiPackageName
        }
    });
    addApis.push(data);
}

function clearAddApisTable() {
    $("#addApisTable").bootstrapTable('destroy');//或者可以调用 removeAll方法
}


function initAddApisTable() {
    $('#addApiPackagesTable').bootstrapTable({
        data: "",
        height: "200",
        search: true,
        iconSize: "outline",
        showRefresh: true,
        showColumns: !0,
        columns: [
            {checkbox: true},
            {
                title: "服务包Id",
                field: "apiPackageId",
                align: "center",
                width: "300"
            }, {
                title: "服務包名称",
                field: "apiPackageName",
                align: "center",
                width: "200"
            }],
        icons: {
            refresh: "glyphicon-repeat",
            toggle: "glyphicon-list-alt",
            columns: "glyphicon-list"
        }
    });
}
function tip_noselect() {
    swal({
        title: "请选择一列数据",
        type: "warning",
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        closeOnConfirm: false
    });
}
function ChangeApiPacge(apiPackageId, addApis, deleteApis) {
    this.apiPackageId = apiPackageId;
    this.addApis = addApis;
    this.deleteApis = deleteApis;
}
function saveCommodity() {
    var apiPackageId = $('#api_packageId').val();
    if (addApis.length > 0 || deleteApis.length > 0) {
        var json = new ChangeApiPacge(apiPackageId, addApis, deleteApis);
        $.ajax({
            url: "/apipackage/change/save",
            type: "post",
            data: JSON.stringify(json),
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            dataType: "json",
            beforeSend: function () {
                // uploading = true;
            },
            success: function (data) {
                if (data.code == 1000) {
                    swal({
                        title: "保存成功",
                        type: "success",
                        confirmButtonText: "确认",
                        closeOnConfirm: false
                    });
                } else {
                    swal({
                        title: "保存失败",
                        type: "error",
                        buttons: false,
                        timer: 1500
                    });
                }
                $('#detailApiPackageModal').modal('hide');
                // location.reload();
            },
            error: function (returndata) {
                alert(returndata);
                $('#detailApiPackageModal').modal('hide');
            }
        });
    } else {
        swal({
            title: "没有变更的数据",
            type: "warning",
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认",
            closeOnConfirm: false
        });
    }
}
function Commodity(commodityId) {
    this.commodityId = commodityId;
}
function detailCommodity(obj) {
    // var commodityId = $('#commodityListTable input:checked').parent().siblings('.commodityId').text();
    var x = $(obj).parent().parent().find("td");
    var commodityId = x.eq(1).text();
    var json = new Commodity(commodityId);
    $.ajax({
        url: "/commodity/info",
        type: "post",
        data: JSON.stringify(json),
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        dataType: "json",
        beforeSend: function () {
            // uploading = true;
        },
        success: function (data) {
            if (data.code == 1000) {
                $('#d_commodityName').val(data.data.commodityName);
                $('#d_price').val(data.data.price);
                $('#d_term').val(data.data.term);
                $('#d_commodityDescription').val(data.data.commodityDescription);
                var apiPackage = data.data.apiPackage;
                $("#detailApiPackagesTable").bootstrapTable('destroy');//或者可以调用 removeAll方法
                initDetailApiPackageTable();
                apiPackage.forEach(function(value,index){
                    var i = $("#detailApiPackagesTable").bootstrapTable('getData').length;
                    $("#detailApiPackagesTable").bootstrapTable('insertRow', {
                        index: i,
                        row: {
                            apiPackageId: value.apiPackageId,
                            apiPackageName: value.apiPackageName
                        }
                    });
                });
                $('#detailCommodityModal').modal('show');
            } else {
                swal({
                    title: "获取详情失败",
                    type: "error",
                    buttons: false,
                    timer: 1500
                });
            }

            // location.reload();
        },
        error: function (returndata) {
            alert(returndata);
        }
    });
}
function initDetailApiPackageTable() {
    $('#detailApiPackagesTable').bootstrapTable({
        data: "",
        height: "200",
        search: true,
        iconSize: "outline",
        showRefresh: true,
        showColumns: !0,
        columns: [
            {checkbox: true},
            {
                title: "服务包Id",
                field: "apiPackageId",
                align: "center",
                width: "300"
            }, {
                title: "服務包名称",
                field: "apiPackageName",
                align: "center",
                width: "200"
            }],
        icons: {
            refresh: "glyphicon-repeat",
            toggle: "glyphicon-list-alt",
            columns: "glyphicon-list"
        }
    });
}
